﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate.Cfg;
using NHibernate;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using System.IO;
using NHibernate.Tool.hbm2ddl;


namespace NHibernateTest
{
    public sealed class HibernateUtil
    {
        private HibernateUtil() { }

        private static ISessionFactory _sessionFactory;
        public static ISessionFactory SessionFactory
        {
            get
            {
                if (null == _sessionFactory)
                {
                    _sessionFactory = CreateSessionFactory();
                    //_sessionFactory = new Configuration()
                    //    .Configure()
                    //    .BuildSessionFactory();
            
                }
                return _sessionFactory;
            }
        }

        public static ISession OpenSession()
        {
            if(null != SessionFactory)
                return SessionFactory.OpenSession();
            return null;
        }

        public static void CloseSession(ISession session)
        {
            if (null != session)
                session.Close();
        }


        private static ISessionFactory CreateSessionFactory()
        {
            return Fluently.Configure()
                .Database(MsSqlConfiguration.MsSql2005
                    .ConnectionString(c => c.Server(@"SABUJ-DAS\SOMA")
                        .Database("emp_db")
                        .Username("sa")
                        .Password("soma"))
                        .ShowSql().FormatSql())
                        .Mappings(m => m.FluentMappings.AddFromAssemblyOf<Program>())
                    .ExposeConfiguration(BuildSchema)
                .BuildSessionFactory();
        }

        private static void BuildSchema(Configuration config)
        {
            
            // this NHibernate tool takes a configuration (with mapping info in)
            // and exports a database schema from it
            new SchemaExport(config)
                .Create(false, true);
        }

    }
}
